package co.edu.unal.bioingenium.kbmed.retrieval.knowledge.process;

import co.edu.unal.bioingenium.kbmed.config.Configuration;
import co.edu.unal.bioingenium.kbmed.features.CompactFeatureVector;
import co.edu.unal.bioingenium.kbmed.knowledge.KnowledgeService;
import co.edu.unal.bioingenium.kbmed.knowledge.vo.DescriptorData;
import co.edu.unal.bioingenium.kbmed.mapping.services.api.MappingService;
import co.edu.unal.bioingenium.kbmed.mapping.services.api.impl.MappingServiceImpl;
import co.edu.unal.bioingenium.kbmed.text.representation.vo.Corpus;
import co.edu.unal.bioingenium.kbmed.retrieval.vo.QueryDocument;
import co.edu.unal.bioingenium.kbmed.retrieval.weighting.TFIDF;
import gnu.trove.map.TObjectIntMap;
import gnu.trove.map.hash.TObjectIntHashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Ing. Alejandro Riveros Cruz
 */
public class QueryByConcepts {

    /**
     * 
     */
    private MappingService mappingService;
    /**
     * 
     */
    private KnowledgeService knowledgeService;
    /**
     * 
     */
    public static int QUERY_FEATURE_TYPE = Configuration.FEATURE_ALL_TO_1;
    /**
     * 
     */
    private int MAX_RETRIEVE_ATTEMPTS = 10;

    /**
     * 
     */
    public QueryByConcepts() {
        mappingService = new MappingServiceImpl(Configuration.MAPPING_SERVICE_ENDPOINT);
        knowledgeService = KnowledgeService.getInstance();
        if (Configuration.QUERY_FEATURE_TYPE.equals("frequency")) {
            QUERY_FEATURE_TYPE = Configuration.FEATURE_FREQUENCY;
        } else if (Configuration.QUERY_FEATURE_TYPE.equals("relativefrequency")) {
            QUERY_FEATURE_TYPE = Configuration.FEATURE_RELATIVE_FREQUENCY;
        } else if (Configuration.QUERY_FEATURE_TYPE.equals("TFIDF")) {
            QUERY_FEATURE_TYPE = Configuration.FEATURE_TF_IDF;
        }
    }

    /**
     * 
     * @param queryString
     * @param corpus
     * @return
     */
    public QueryDocument mapQueryToConcepts(String queryString, Corpus corpus) {
        TObjectIntMap<String> queryWords = callMappingService(queryString, corpus);
        QueryDocument queryDocument = new QueryDocument(queryString);
        queryDocument.setWordList(queryWords);
        extractQueryFeatures(queryDocument, corpus);
        return queryDocument;
    }

    /**
     * 
     * @param queryString
     * @param corpus
     * @param givenDescriptorIds
     * @return
     */
    public QueryDocument mapQueryToConcepts(String queryString, Corpus corpus, Set<String> givenDescriptorIds) {
        TObjectIntMap<String> queryWords = callMappingService(queryString, corpus);
        QueryDocument queryDocument = new QueryDocument(queryString);
        for (String descriptorId : givenDescriptorIds) {
            queryWords.put(descriptorId, 1);
        }
        queryDocument.setWordList(queryWords);
        extractQueryFeatures(queryDocument, corpus);
        return queryDocument;
    }

    /**
     * 
     * @param queryDocument
     * @param corpus
     * @param givenDescriptorIds
     * @return
     */
    public QueryDocument mapQueryToConcepts(QueryDocument queryDocument, Corpus corpus, Set<String> givenDescriptorIds) {
        for (String descriptorId : givenDescriptorIds) {
            queryDocument.getWordList().put(descriptorId, 1);
        }
        extractQueryFeatures(queryDocument, corpus);
        return queryDocument;
    }

    /**
     *
     * @param queryString
     * @param corpus
     * @return  
     */
    private TObjectIntMap<String> callMappingService(String queryString, Corpus corpus) {
        TObjectIntMap<String> queryWords = new TObjectIntHashMap<String>();
        List<DescriptorData> foundConcepts;
        try {
            int retrieveAttempts = 0;
            boolean isProcessed = false;
            String key = mappingService.doMapping(queryString);
            while (!(isProcessed = mappingService.isProcessed(key))) {
                Thread.sleep(200);
                retrieveAttempts++;
                if (retrieveAttempts == MAX_RETRIEVE_ATTEMPTS) {
                    break;
                }
            }
            if (isProcessed) {
                foundConcepts = mappingService.getAllConcepts(key);
                for (DescriptorData descriptorData : foundConcepts) {
                    if (queryWords.containsKey(descriptorData.getDescriptorId())) {
                        queryWords.increment(descriptorData.getDescriptorId());
                    } else {
                        queryWords.put(descriptorData.getDescriptorId(), 1);
                    }
                }
            }
            return queryWords;
        } catch (InterruptedException ex) {
            Logger.getLogger(QueryByConcepts.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    /**
     * 
     * @param queryDocument
     */
    public void expandConcepts(QueryDocument queryDocument) {
        Set<String> surgeryConcepts = getSurgeryConcepts(queryDocument);
        TObjectIntMap<String> queryWords = queryDocument.getWordList();
        for (String conceptId : surgeryConcepts) {
            if (queryWords.containsKey(conceptId)) {
                queryWords.increment(conceptId);
            } else {
                queryWords.put(conceptId, 1);
            }
        }
        queryDocument.setWordList(queryWords);
    }

    /**
     * 
     * @param queryDocument
     * @return
     */
    public Set<String> getSurgeryConcepts(QueryDocument queryDocument) {
        Set<String> tempSet = new HashSet<String>();
        for (String conceptId : queryDocument.getWordList().keySet()) {
            tempSet.retainAll(knowledgeService.getNeighborsByConceptId(conceptId));
        }
        return tempSet;
    }

    /**
     *
     * @param queryDocument
     * @param corpus 
     */
    public void extractQueryFeatures(QueryDocument queryDocument, Corpus corpus) {
        TObjectIntMap<String> invertedSortedWordList = corpus.getInvertedSortedWordList();
        float value;
        CompactFeatureVector featureVector = new CompactFeatureVector();
        switch (QueryByConcepts.QUERY_FEATURE_TYPE) {
            case Configuration.FEATURE_FREQUENCY:
                for (String word : queryDocument.getWordList().keySet()) {
                    value = (float) queryDocument.getWordList().get(word);
                    featureVector.setValue(invertedSortedWordList.get(word), value);
                }
                break;
            case Configuration.FEATURE_RELATIVE_FREQUENCY:
                for (String word : queryDocument.getWordList().keySet()) {
                    value = (float) queryDocument.getWordList().get(word) / (float) queryDocument.getWordList().size();
                    featureVector.setValue(invertedSortedWordList.get(word), value);
                }
                break;
            case Configuration.FEATURE_TF_IDF:
                for (String word : queryDocument.getWordList().keySet()) {
                    value = (float) TFIDF.getTFIDF(queryDocument.getWordList().get(word), queryDocument.getWordList().size(), corpus.getTotalDocuments() + 1, corpus.getDocumentOcurrences(word) + 1);
                    featureVector.setValue(invertedSortedWordList.get(word), value);
                }
                featureVector.normalize();
                break;
            case Configuration.FEATURE_ALL_TO_1:
                for (String word : queryDocument.getWordList().keySet()) {
                    featureVector.setValue(invertedSortedWordList.get(word), 1f);
                }
                featureVector.normalize();
                break;
        }
        queryDocument.setFeatureVector(featureVector);
    }
}
